import { Component, Injector } from '@angular/core';
import { AppComponentBase } from '@shared/common/app-component-base';
import { GetNodeListDto, GetNodeListType, WorkFlowServiceProxy } from '@shared/service-proxies/service-proxies';
import { BsModalRef } from 'ngx-bootstrap/modal';
import { merge as _merge } from 'lodash-es';
import { finalize } from 'rxjs/operators';

@Component({
    templateUrl: './back-selection-modal.component.html'
})
export class BackSelectionModelComponent extends AppComponentBase {

    callback: {(data:{[key:string]:any}):void};

    isShown = false;
    isInitialized = false;

    loading = false;
    saving = false;

    nodeList: GetNodeListDto[] = [];
    selectNodeId: string = '';

    constructor(
        injector: Injector,
        public bsModalRef: BsModalRef,
        private _workFlowServiceProxy:WorkFlowServiceProxy,
    ) {
        super(injector);
    }

    close(): void {
        this.bsModalRef.hide();
    }

    shown(paperId: string, type: GetNodeListType, nodeId: string): void {
        this.isShown = true;
        
        this.loading = true;
        this._workFlowServiceProxy.getNodeList(paperId, type)
            .pipe(finalize(() => { this.loading = false; }))
            .subscribe(result => {
                this.nodeList = result.nodeList;
                if (this.nodeList.length > 0) {
                    this.selectNodeId = this.nodeList[0].value;
                }
            });

        this.isInitialized = true;
    }

    save() {
        this.callback({ selectNodeId: this.selectNodeId });
        this.close();
    }
}
